package com.zk.babala.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlightHelper;
import androidx.leanback.widget.HorizontalGridView;
import androidx.leanback.widget.ItemBridgeAdapter;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.VerticalGridView;

import com.bumptech.glide.Glide;
import com.zk.babala.BabalaApp;
import com.zk.babala.R;
import com.zk.babala.entity.Movie;
import com.zk.babala.entity.PlayNumInfo;
import com.zk.babala.entity.VideoInfo;
import com.zk.babala.util.Constant;
import com.zk.babala.util.HistoryUtil;

import java.io.Serializable;
import java.util.List;

/*
 * Details activity class that loads LeanbackDetailsFragment class
 */
public class DetailsActivity extends Activity {
    public static final String MOVIE = "Movie";
    private Movie movie;
    ImageView imageView;
    TextView playHisTextView = null;
    Button delHisButton = null;
    Button playNextButton = null;
    HorizontalGridView lineGridView;
    VerticalGridView itemGridView;
    ArrayObjectAdapter lineAdapter = null;
    VideoInfo videoDetail = null;
    LinearLayout infoLinerLayout = null;
    LinearLayout info2LinerLayout = null;
    TextView titleView;
    TextView descView;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_activity);
        movie = (Movie) getIntent().getSerializableExtra(DetailsActivity.MOVIE);
        assert movie != null;
        String url = movie.getVideoUrl();
        imageView = findViewById(R.id.detail_image);
        Glide.with(this).load(movie.getCardImageUrl())
                .placeholder(R.drawable.default_movie_image) // 加载中显示默认图片
                .error(R.drawable.default_movie_image).into(imageView);
        playHisTextView = findViewById(R.id.play_his);
        delHisButton = findViewById(R.id.delHisButton);
        playNextButton = findViewById(R.id.playNextButton);
        infoLinerLayout = findViewById(R.id.info_liner_layout);
        info2LinerLayout = findViewById(R.id.info2_liner_layout);
        titleView = findViewById(R.id.detail_title);
        titleView.setText(movie.getTitle());
        descView = findViewById(R.id.detail_desc);
        videoDetail = BabalaApp.getSourceParse().getVideoDetail(url);
        processDetailInfoList(videoDetail.getDetailInfoList());
        LinePresenter();
        setHisTitle();
    }

    private void LinePresenter() {
        lineGridView = findViewById(R.id.line_list);
        lineGridView.setNumRows(1);
        LinePresenter presenter = new LinePresenter();
        //创建ObjectAdapter，用于提供数据，当有多种类型时，传入PresenterSelector
        lineAdapter = new ArrayObjectAdapter(presenter);
        if (videoDetail.getLineInfoList() == null) {
            return;
        }
        videoDetail.getLineInfoList().forEach(lineInfo -> {
            lineAdapter.add(lineInfo.getTitle());
        });
        ItemBridgeAdapter bridgeAdapter = new ItemBridgeAdapter(lineAdapter);
        lineGridView.setAdapter(bridgeAdapter);
        FocusHighlightHelper.setupHeaderItemFocusHighlight(bridgeAdapter);
        if (lineAdapter.size() > 0) {
            itemListView(lineAdapter.get(0).toString());
        }
    }

    //当前播放线路
    private List<PlayNumInfo> currLinePlayNumList = null;

    private void itemListView(String line) {
        currLinePlayNumList = videoDetail.getLineInfoList().stream().filter(l -> l.getTitle().equals(line)).findFirst().get().getPlayNumInfoList();
        itemGridView = findViewById(R.id.line_item_list);
        itemGridView.setNumColumns(10);
        ItemPresenter presenter = new ItemPresenter();
        //创建ObjectAdapter，用于提供数据，当有多种类型时，传入PresenterSelector
        ArrayObjectAdapter objectAdapter = new ArrayObjectAdapter(presenter);
        objectAdapter.addAll(0, currLinePlayNumList);
        ItemBridgeAdapter bridgeAdapter = new ItemBridgeAdapter(objectAdapter);
        //将ItemBridgeAdapter传入HorizontalGridView
        itemGridView.setAdapter(bridgeAdapter);
        itemGridView.requestFocus();
        //设置上焦动画
        FocusHighlightHelper.setupHeaderItemFocusHighlight(bridgeAdapter);
    }


    private class LinePresenter extends Presenter {
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup) {
            View inflate = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.play_line, viewGroup, false);
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, Object item) {
            Button textView = viewHolder.view.findViewById(R.id.lineText);
            textView.setText(item.toString());
            textView.setOnClickListener(v -> {
                itemListView(item.toString());
                setHisTitle();
            });

        }

        @Override
        public void onUnbindViewHolder(ViewHolder viewHolder) {
        }

    }

    private class ItemPresenter extends Presenter {
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup) {
            View inflate = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.play_item, viewGroup, false);
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, Object item) {
            PlayNumInfo playNum = (PlayNumInfo) item;
            Button button = viewHolder.view.findViewById(R.id.playItemButton);
            button.setText(playNum.getTitle());
            if (playNum.getPageUrl() == null) {
                return;
            }

            button.setOnClickListener(v -> {
                startPlay(viewHolder.view.getContext(), playNum);
            });
        }

        @Override
        public void onUnbindViewHolder(ViewHolder viewHolder) {
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!lineGridView.hasFocus()) {
                lineGridView.requestFocus();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setHisTitle();
    }

    public void setHisTitle() {
        playNextButton.setVisibility(View.GONE);
        delHisButton.setVisibility(View.GONE);
        Movie hisMovie = HistoryUtil.getHistoryInstance().getPlayHis(movie);
        lineGridView.requestFocus();
        if (hisMovie != null) {
            delHisButton.setVisibility(View.VISIBLE);
            playHisTextView.setText(String.format("当前播放:%s", hisMovie.getPlayHis()));
            delHisButton.setOnClickListener(view -> {
                HistoryUtil.getHistoryInstance().delPlayHis(movie);
                Toast.makeText(view.getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                playHisTextView.setText("");
                delHisButton.setVisibility(View.GONE);
                playNextButton.setVisibility(View.GONE);
            });
            if (currLinePlayNumList != null) {
                int nextId = hisMovie.getId() + 1;
                if (currLinePlayNumList.size() > nextId) {
                    PlayNumInfo playNum = currLinePlayNumList.get(nextId);
                    playNextButton.setVisibility(View.VISIBLE);
                    playNextButton.requestFocus();
                    playNextButton.setText(playNum.getTitle());
                    playNextButton.setOnClickListener(view -> {
                        startPlay(view.getContext(), playNum);
                    });
                }
            }

        }
    }

    private void startPlay(Context context, PlayNumInfo playNum) {
        Intent intent;
        if (Constant.PLAY_TYPE_WEBVIEW.equals(playNum.getPlayType())) {
            intent = new Intent(context, WebViewActivity.class);
        } else {
            intent = new Intent(context, VideoActivity.class);
        }
        intent.putExtra("movie", movie);
        intent.putExtra("playNum", playNum);
        intent.putExtra("currLinePlayNumList", (Serializable) currLinePlayNumList);
        context.startActivity(intent);
    }


    /**
     * 处理详细信息列表
     *
     * @param detailInfoList 详细信息列表
     */
    private void processDetailInfoList(List<String> detailInfoList) {
        if (detailInfoList.isEmpty()) {
            return;
        }
        int size = detailInfoList.size();
        for (int i = 0; i < size; i++) {
            String text = detailInfoList.get(i);
            if (i == size - 1) {
                descView.setText(text);
                continue;
            }
            if (text.length() > 10) {
                text = text.substring(0, 10);
            }
            TextView textView = createTextView(text);
            if (i < size / 2) {
                infoLinerLayout.addView(textView);
            } else {
                info2LinerLayout.addView(textView);
            }
        }

    }


    private TextView createTextView(String text) {
        TextView textView = new TextView(this);
        textView.setText(text);
        textView.setTextSize(14); // 设置字体大小
        textView.setTextColor(ContextCompat.getColor(this, R.color.choice_normal)); // 设置文字颜色

        // 设置布局参数
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 4, 0, 4); // 设置间距
        textView.setLayoutParams(params);

        return textView;
    }

}